<template>
	<view>

		<myMap ref="myMap" :points="points"></myMap>

		<view class="page-bottom mp-iphonex-bottom" id="pageBottom">
			<view class="icon-btn">
				<view class="icon-btn-item" @click="pauseRun()">
					<u-icon size="34" class="red" name="home-fill"></u-icon>
					<view class="red icon-btn-name">暂停</view>
				</view>
				<view class="icon-btn-item" @click="startRun()">
					<u-icon size="34" class="red" name="home-fill"></u-icon>
					<view class="red icon-btn-name">开始跑步</view>
				</view>
				<view class="icon-btn-item" @click="stopRun()">
					<u-icon size="34" name="kefu-ermai"></u-icon>
					<view class="icon-btn-name">结束</view>
				</view>
			</view>
			<view>
				<view>本次运动{{totalDistance}}m</view>
				<view>目标公里数5km</view>
			</view>
			<view @click="init()">测试按钮</view>
		</view>

	</view>
</template>


<script>
	import myMap from "./map.vue"
	import {
		testSend
	} from '@/api/activate.js'
	import {
		uploadGps,
		getHistoryRunData
	} from '@/api/run.js'
	export default {
		// mixins: [onShareAppMessage],
		components: {
			myMap
		},
		name: "index",
		data() {
			return {
				switchGPS: false,
				totalDistance: 0.0,
				histroyDistance: 0.0,
				activateId: undefined,
				share: {
					// title: this.share.title,
					// path: this.share.path,
					// imageUrl: this.share.imageUrl,
					// desc: this.share.desc,
					// content: this.share.content,
				},

				points: [],
				activateList: [],
				// imageLoaded: false,
			}
		},
		mounted() {},
		onUnload() {
			uni.reLaunch({
				"url": "/pages/index/index"
			});
			// console.log("hedojasjkod")
		},
		onShow() {
			this.init()
			console.log("============")
			let userInfo = this.$store.state;
			testSend(userInfo).then(res => {
				// console.log("res=>", res)
				if (res.statusCode === 200 && res.data.code === 0) {
					this.activateList = res.data.data.list;
					console.log("res.data.list=>", res.data.data.list)
				} else {
					console.error('Fetch failed with response:', res.data);
				}
			})
			// console.log("userInfo=>", userInfo);
			console.log("onShow");
			// this.fetchActivateList();

			//加载测试数据
			this.testData();
		},

		onLoad(options) {
			console.log("onLoad");
			this.activateId = options.activateId
		},
		methods: {

			async init() {
				let res = await getHistoryRunData(this.$store.state.user.id, this.activateId)
				console.log("this.init =>", res)
				// 计算累计跑步多少
				res.data.data.regps.forEach((item, index) => {
					console.log(`regps item ${index}:`, item);
					if (item.gPSdata.length > 0) {
						this.histroyDistance = this.histroyDistance + this.calculateTotalDistance(item.gPSdata)
					}
					// 遍历 gPSdata
					item.gPSdata.forEach((gpsItem, gpsIndex) => {
						console.log(`gPSdata item ${gpsIndex} for regps item ${index}:`, gpsItem);
					});
				});
			},
			startRun() {
				console.log("startRun")
				this.startGetLocation()
			},
			async stopRun() {
				console.log("stopRun");
				console.log(this.$refs.myMap)
				let res = this.$refs.myMap.clearData(); // 调用子组件的清空方法
				console.log("test", res)
				const uploadRes = await uploadGps(res.markers, this.$store.state.user.id, this.activateId)
				console.log("uploadRes =>", uploadRes)
				let totalDistance = this.calculateTotalDistance(res.markers);
				// console.log("Total distance: " + totalDistance + " meters");
				this.totalDistance = totalDistance
				// console.log("Sending data to backend...", this.points);
				this.points = [];
				uni.stopLocationUpdate({
					success: res => console.log('开启小程序接收位置消息成功'),
					fail: err => console.error('开启小程序接收位置消息失败：', err),
					complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
				});
			},

			pauseRun() {
				console.log("pauseRun")
				uni.stopLocationUpdate({
					success: res => console.log('开启小程序接收位置消息成功'),
					fail: err => console.error('开启小程序接收位置消息失败：', err),
					complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
				});
			},
			calculateTotalDistance(markers) {
				let totalDistance = 0;
				for (let i = 0; i < markers.length - 1; i++) {
					const distance = this.calculateDistance(
						markers[i].latitude, markers[i].longitude,
						markers[i + 1].latitude, markers[i + 1].longitude
					);
					totalDistance += distance;
				}
				return totalDistance;
			},
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371e3; // 地球半径(m)
				const φ1 = lat1 * Math.PI / 180; // φ, λ 弧度制
				const φ2 = lat2 * Math.PI / 180;
				const Δφ = (lat2 - lat1) * Math.PI / 180;
				const Δλ = (lon2 - lon1) * Math.PI / 180;

				const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
					Math.cos(φ1) * Math.cos(φ2) *
					Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

				const distance = R * c; // (m)
				return distance;
			},
			tabSelect(e) {
				const index = e.currentTarget.dataset.id;
				this.TabCur107 = index;
				// 根据选中的 Tab 加载不同的数据
				this.loadDataForTab(index);
			},

			loadDataForTab(index) {
				console.log('加载数据 for tab:', index);
				if (index == 1) {
					this.startGetLocation()
					this.switchGPS = true;
				} else {
					if (this.switchGPS) {
						//结束GPS
						uni.stopLocationUpdate({
							success: res => console.log('开启小程序接收位置消息成功'),
							fail: err => console.error('开启小程序接收位置消息失败：', err),
							complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
						});
						this.switchGPS = false
					}

				}
			},
			onShareAppMessage(res) {
				return {
					path: this.share(),
					title: `请快来帮我砍一刀${this.bargainDetail.goodsName}`,
				};
			},
			testData() {
				console.log("测试用");
				// 这里均为测试开发用
				this.activateList.push({
					"title": "测试数据1",
					"url": "https://ossweb-img.qq.com/images/lol/web201310/skin/big37006.jpg"
				}, {
					"title": "测试数据1",
					"url": "https://ossweb-img.qq.com/images/lol/web201310/skin/big37006.jpg"
				}, {
					"title": "测试数据1",
					"url": "https://ossweb-img.qq.com/images/lol/web201310/skin/big37006.jpg"
				}, {
					"title": "测试数据1",
					"url": "https://ossweb-img.qq.com/images/lol/web201310/skin/big37006.jpg"
				});
			},
			changePage(ID, state) {
				console.log("hello world,ID state =>", ID, state)
				uni.navigateTo({
					url: `/main/run/activate?acitvate=${ID}&state=${state}`
				});
			},
			startGetLocation: function() {
				let that = this;
				uni.startLocationUpdate({
					success: res => {
						uni.onLocationChange(function(res2) {
							uni.showToast({
								title: '经度：' + res2.longitude + '纬度：' + res2.latitude +
									"速度 (m/s)" + res2.speed + "精确:" + res2.accuracy,
								icon: 'none',
							});
							let newPoint = {
								latitude: res2.latitude,
								longitude: res2.longitude,
								speed: res2.speed
							};
							console.log(newPoint)
							that.points.push(newPoint);
							// 动态更新地图轨迹
							// that.setDateByPoints(that.points);

						});
					},
					fail: err => {
						uni.showToast({
							title: err,
							icon: 'none',
						});
					},
					complete: msg => console.log('调用开启小程序接收位置消息 API 完成')
				});
			},

		},

	}
</script>


<style lang="scss" scoped>
	@import "./activate.scss";

	$w_94: 94%;

	.layout {
		padding: 8px 0;
		background: #f9f9f9;
	}

	.selected-title {
		>h4 {
			font-size: 30rpx;
			color: #000 !important;
		}

		>view {
			font-weight: bold;

		}
	}

	.goods-cell-title {
		background: #f9f9f9;
		padding: 10px;
		transition: 0.35s;
		display: flex;
		float: left;

		>.goods-item-title {
			flex: 1;
			text-align: center;

			>h4 {
				font-size: 32rpx;
			}

			>view {
				color: #999;
				font-size: 24rpx;
			}
		}
	}

	.goods-list {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}

	.goods-item {
		width: 50%;
		height: 40vw;
		margin-bottom: 10px;
		border-radius: 0.4em;
		overflow: hidden;
	}

	.goods-img {
		position: relative;
		margin: 0 auto;
		// width: 100%;
		height: 40%;
		width: $w_94;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		overflow: hidden;
	}

	.goods-desc {
		border-bottom-left-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
		width: $w_94;
		background: #fff;
		padding: 8rpx 0 8rpx 8rpx;
		margin: 0 auto;

		>.goods-title {
			font-size: 24rpx;
			height: 67rpx;
			display: -webkit-box;
			font-weight: 500;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
		}

		>.goods-bottom {
			display: flex;
			font-weight: bold;

			>.goods-price {
				line-height: 2;


				>span {
					font-size: 42rpx;
				}
			}
		}
	}
</style>